package com.yunqian.web;

import com.yunqian.common.CurrentUser;
import com.yunqian.exception.BaseException;
import com.yunqian.jwt.JwtUser;
import com.yunqian.redot.domain.Users;
import com.yunqian.redot.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UsersService userService;

    /**
     * 获取分页
     *
     * @param params
     * @return
     */
    @PostMapping("/pagination")
    public Page<Users> pagination(@RequestBody Map<String, Object> params) {
        return userService.pagination(params);
    }

    /**
     * 局部更新数据
     *
     * @param id         待更新id
     * @param modifyData 待更新的数据
     * @return
     */
    @PutMapping("/{id}")
    public Users update(@PathVariable("id") Long id, @RequestBody Map<String, Object> modifyData) {
        return userService.update(id, modifyData);
    }


    /**
     * 新增
     *
     * @param user
     */
    @PostMapping
    public Users save(@RequestBody @Valid Users user) {
        return userService.save(user);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Users detail(@PathVariable("id") Long id) {
        return userService.findStrictOne(id);
    }

    /**
     * 获取当前用户信息
     *
     * @param user
     * @return
     */
    @GetMapping("curr_user")
    public Users currUserInfo(@CurrentUser JwtUser user) {
        Users currUser = userService.findStrictOne(user.getId());
        currUser.setPassword(null);
        return currUser;
    }

    /**
     * 用户自己修改密码
     *
     * @return
     */
    @PutMapping("/reset")
    public Users updatePassword(@RequestBody Map<String, Object> map,@CurrentUser JwtUser user) {
        if (!map.containsKey("old_password") || map.get("old_password").toString().length() <= 0) {
            throw new BaseException("旧密码不能为空");
        }
        if (!map.containsKey("password") || map.get("password").toString().length() <= 0) {
            throw new BaseException("新密码不能为空");
        }
        return userService.updatePassword(user.getId(),map);
    }
}
